package sms

import (
	"gitee.com/mootok/mootok/src/constant/config"
	"gitee.com/mootok/mootok/src/constant/strings"
	"gitee.com/mootok/mootok/src/services/sms"
	"gitee.com/mootok/mootok/src/utils/logging"
	"gitee.com/mootok/mootok/src/web/api"
	"gitee.com/mootok/mootok/src/web/common/response"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"math/rand"
	"net/http"
	"strconv"
)

type ApiSmsImpl struct {
}

var Service sms.Service

func (*ApiSmsImpl) SendSmsRegisterAndLoginCode(c *gin.Context) {
	logger := logging.LogService("Sms.Request").WithContext(c.Request.Context())
	smsRegisterAndLoginReq := api.SmsRegisterAndLoginCodeReq{}

	err := c.ShouldBindJSON(&smsRegisterAndLoginReq)
	if err != nil {
		response.FailWithMsg(c, http.StatusBadRequest, strings.ParamsErrorCode, strings.ParamsError)
		return
	}

	code := strconv.Itoa(rand.Intn(900000) + 100000)
	phone := smsRegisterAndLoginReq.Phone
	err = Service.SendAuthCode(c, phone, code)
	//限流
	allow, err := Service.RegisterAndLoginSmsLimit(c, phone)
	if err != nil {
		response.FailWithMsg(c, http.StatusInternalServerError, strings.RedisOperationErrorCode, strings.InternalServiceError)
		logger.Errorf("limiter.Allow: %s", err.Error())
		return
	}

	if allow == false {
		logger.Errorf("ratelimit hit.")
		response.FailWithMsg(c, http.StatusInternalServerError, strings.RateLimitHitErrorCode, strings.RateLimitHit)
		return
	}
	if err != nil {
		logger.WithFields(logrus.Fields{
			"phone": phone,
			"code":  code,
		}).Errorf("Error writing to code to redis:%v", err)
		response.FailWithMsg(c, http.StatusInternalServerError,
			strings.RedisKeyNotFoundErrorCode, strings.InternalServiceError)
		return
	}
	logger.WithFields(logrus.Fields{
		"phone": phone,
		"code":  code,
	}).Errorf("Code generated success.")

// 响应验证码仅用于测试环境
	if config.EnvConfig.IsProduction() {
		response.SuccessWithDetail(c, strings.SuccessCode, strings.Success, &api.SmsCodeResp{Code: nil})
	} else {
		response.SuccessWithDetail(c, strings.SuccessCode, strings.Success, &api.SmsCodeResp{Code: &code})
	}
}
